#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2019/10/17 10:45
# @Author  : ZRD
# @File    : rsa_test3.py

"""
pip install rsa

1. 私钥,公钥保存
"""

import rsa
import base64

pubkeyfilename = 'public.pem'
privatefilename = "private.pem"


# 生成一对密钥并保存
def pubkey_privkey_gensave():
    (pubkey, privkey) = rsa.newkeys(2048)

    # 公钥
    pub = pubkey.save_pkcs1()
    pubfile = open(pubkeyfilename, 'wb')
    pubfile.write(pub)
    pubfile.close()

    # 私钥
    pri = privkey.save_pkcs1()
    prifile = open(privatefilename, 'wb')
    prifile.write(pri)
    prifile.close()


# 加载公钥私钥
def load_pubkey_privkey(publicfilepath, privatefilepath):
    with open(publicfilepath) as publickfile:
        pub = publickfile.read().encode()
        pubkey = rsa.PublicKey.load_pkcs1(pub)

    with open(privatefilepath) as privatefile:
        pri = privatefile.read().encode()
        privkey = rsa.PrivateKey.load_pkcs1(pri)
    print(f"加载的公钥: {pubkey}")
    print(f"加载的私钥: {privkey}")

    return pubkey, privkey


if __name__ == '__mai1n__':
    """
        方法1
    """
    # pubkey_privkey_gensave()
    pubkey, prikey = load_pubkey_privkey(pubkeyfilename, privatefilename)

    message = "你好"

    # 用公钥加密，并用Base64编码后输出
    crypto = rsa.encrypt(message.encode('utf-8'), pubkey)
    crypto64 = base64.b64encode(crypto)
    print(f"base64密文: {str(crypto64)}")

    # 通过Base64解码，用私钥解密
    crypto = base64.b64decode(crypto64)
    resmessage = rsa.decrypt(crypto, prikey).decode('utf-8')
    print(f"使用私钥解密得到的明文: {resmessage}")

if __name__ == '__main__':
    """
        方法2
    """
    # pubkey_privkey_gensave()
    pubkey, prikey = load_pubkey_privkey(pubkeyfilename, privatefilename)

    message = "你好"

    # 用公钥加密，并用Base64编码后输出
    sign_hash= rsa.sign(message.encode('utf-8'), prikey, 'SHA-1')
    print(f"sign_hash: {sign_hash}")
    pass

    # crypto64 = base64.b64encode(crypto)
    # print(f"base64密文: {str(crypto64)}")
    #
    # # 通过Base64解码，用私钥解密
    # crypto = base64.b64decode(crypto64)
    # resmessage = rsa.decrypt(crypto, prikey).decode('utf-8')
    # print(f"使用私钥解密得到的明文: {resmessage}")
